import { sys } from "cc";

export interface S2048_GameStorageData {
    high_score: number;
}

/** 存储类，用于存储需要本地保存的数据 */
class S2048_GameStorage {
    data: S2048_GameStorageData = null;
    defaultValue: S2048_GameStorageData = null;

    private static _instance: S2048_GameStorage = null;

    static get instance(): S2048_GameStorage {
        this._instance = this._instance || new S2048_GameStorage();
        return this._instance;
    }

    initData() {
        this.InitDefaultData();

        let dataStr = sys.localStorage.getItem(`S2048_GameStorage`);
        if (!dataStr || dataStr === "") {
            this.clearData();
        } else {
            this.data = JSON.parse(dataStr);
            this.saveData();
        }

        this.SetEveryData();
    }

    // 初始化默认值
    InitDefaultData() {
        this.defaultValue = {
            high_score: 0,
        };
    }

    SetEveryData() {
        for (let key in this.defaultValue) {
            let defaultValue = this.defaultValue[key];
            let dataValue = this.data[key];
            // console.log(key, defaultValue, dataValue);
            if (dataValue === null || dataValue === undefined) {
                this.data[key] = defaultValue;
            }
        }
        this.saveData();
    }

    clearData() {
        this.data = { ...this.defaultValue };
    }

    saveData() {
        let dataStr = JSON.stringify(this.data);
        sys.localStorage.setItem(`S2048_GameStorage`, dataStr);
    }
}

export default S2048_GameStorage.instance;